<?php

	$edit = !empty($_POST['cmd_save']);
	$add = !empty($_POST['cmd_add']);

	// check mode
	if ($edit || $add) {

		// id is required for edit mode
		$id = 0;
		if ($edit) {
			$id = (int)$_GET['id'];
			if (!$id)
				return;
		}

		// check entry
		if (!ereg('^([0-9a-f]{32})$', $_POST['fgsd_key']))
			$error[] = tr('Key must be hexadecimal string with exactly 32 chars');
		if ($add && empty($_POST['fgsd_pwd']))
			$error[] = tr('No password provided');
		if (!ereg('^([0-9a-zA-Z\-_ ]{3,})$', $_POST['fgsd_name']))
			$error[] = tr('Name must have 3 chars minimum');
		if (empty($_POST['owner_id']) && empty($_POST['owner_name']))
			$error[] = tr('Owner must be an ID or a Name');

		// quit if errors occured
		if (count($error)) {
			if ($add)
				$_POST['add'] = 1;
			else if ($edit)
				$_POST['edit'] = 1;
			return;
		}

		$sql = new sql();
		// construct sql query
		$query = sprintf('
			%s fgs_fgsd
			SET
				fgsd_key = "%s",
				fgsd_pwd = %s,
				fgsd_name = "%s",
				fgsd_isblacklisted = %d,
				owner_id = %s,
				owner_name = %s
			%s',
			$edit ? 'UPDATE' : 'INSERT',
			mysql_real_escape_string($_POST['fgsd_key']),
			empty($_POST['fgsd_pwd']) ? 'fgsd_pwd' : sprintf('"%s"', md5($_POST['fgsd_pwd'])),
			mysql_real_escape_string($_POST['fgsd_name']),
			$_POST['fgsd_isblacklisted'] == 'on' ? 1 : 0,
			empty($_POST['owner_id']) ? 'NULL' : sprintf('%d', $_POST['owner_id']),
			empty($_POST['owner_name']) ? 'NULL' : sprintf('"%s"', mysql_real_escape_string($_POST['owner_name'])),
			$edit ?
				sprintf('WHERE id = %d', $id) :
				', dt_create = NOW()'
		);

		// execute query
		$sql->query($query);

	}


?>
